package com.loong.service.impl;

import com.loong.mapper.CartMapper;
import com.loong.mapper.ItemMapper;
import com.loong.mapper.OrderMapper;
import com.loong.mapper.impl.CartMapperImpl;
import com.loong.mapper.impl.ItemMapperImpl;
import com.loong.mapper.impl.OrderMapperImpl;
import com.loong.pojo.Cart;
import com.loong.pojo.Item;
import com.loong.pojo.Orders;
import com.loong.service.OrderService;
import com.loong.utils.RandomUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class OrderServiceImpl implements OrderService {

    @Override
    public void createOrder(String aid, String uid, String sum) {
        Orders orders = new Orders();
        BigDecimal bigDecimal = new BigDecimal(sum);
        String orderId = RandomUtils.createOrderId();
        orders.setOid(orderId);
        orders.setAid(Integer.parseInt(aid));
        orders.setUid(Integer.parseInt(uid));
        orders.setOprice(bigDecimal);
        orders.setOtime(new Date());
        orders.setOstate(1);
        OrderMapper orderMapper = new OrderMapperImpl();
        orderMapper.insertOrders(orders);

        CartMapper cartMapper = new CartMapperImpl();
        List<Cart> carts = cartMapper.selectCartsByUid(Integer.parseInt(uid));

        ItemMapper itemMapper = new ItemMapperImpl();
        for (Cart cart : carts) {
            Item item = new Item();
            item.setOid(orderId);
            item.setPid(cart.getProduct().getPid());
            item.setInum(cart.getCnum());
            item.setIprice(cart.getCprice());
            itemMapper.insertItem(item);
        }
        cartMapper.deleteCartByUid(Integer.parseInt(uid));
    }

    @Override
    public List<Orders> findOrderByUid(Integer uid) {
        OrderMapper orderMapper = new OrderMapperImpl();
        List<Orders> orders = orderMapper.selectOrderByUid(uid);
        return orders;
    }

    @Override
    public Orders findOrderByOid(String oid) {
        OrderMapper orderMapper = new OrderMapperImpl();
        //订单和地址
        Orders orders = orderMapper.selectOrderByOid(oid);
        //订单和商品
        ItemMapper itemMapper = new ItemMapperImpl();
        List<Item> items = itemMapper.selectItemByOid(oid);
        for (Item item : items) {
            System.out.println(item);
        }
        orders.setItems(items);
        return orders;
    }

    @Override
    public void updateStateByOid(String oid) {
        OrderMapper orderMapper = new OrderMapperImpl();
        orderMapper.updateStateByOid(oid);
    }

    @Override
    public void updateStateToFourByOid(String oid) {
        OrderMapper orderMapper = new OrderMapperImpl();
        orderMapper.updateStateToFourByOid(oid);
    }
}
